package com.zhc.dejingapi.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class httpUtils {



    public static String sendPost(String url, String param){
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try{
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            // 创建URL对象
            URL realUrl = new URL(urlNameString);
            // 打开URL连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-type", "application/json");
            // 设置POST方法
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnetion对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null){
                result.append(line);
            }
            log.info("data - {}",param);
            log.info("recv - {}", result);
        }
        catch (ConnectException e){
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }catch (SocketTimeoutException e){
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }catch (IOException e){
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }catch (Exception e){
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally{
            try{
                if (out != null){
                    out.close();
                }
                if (in != null){
                    in.close();
                }
            }catch (IOException ex){
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

//    原文链接：https://blog.csdn.net/BINGGANLINGSHI/article/details/121283977
}
